package com.yumo.kangchenjunga.security;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.yumo.kangchenjunga.user.NoSuchUserException;
import com.yumo.kangchenjunga.user.UserService;

public class CustomUserPasswordEncoder implements PasswordEncoder {

	public static String username;
	public static String companyId;

	@Autowired
	private UserService userService;

	private final Log logger = LogFactory.getLog(getClass());

	@Override
	public String encode(CharSequence rawPassword) {
		return DigestUtils.sha256Hex(getSalt() + rawPassword);
	}

	@Override
	public boolean matches(CharSequence rawPassword, String encodedPassword) {
		if (encodedPassword == null || encodedPassword.length() == 0) {
			logger.warn("Empty encoded password");
			return false;
		}

		return StringUtils.equals(DigestUtils.sha256Hex(getSalt() + rawPassword), encodedPassword);
	}

	private String getSalt() {
		String salt = "";
		try {
			salt = userService.query(username, StringUtils.isBlank(companyId) ? 1 : Integer.valueOf(companyId)).salt;
		} catch (NoSuchUserException e) {
			e.printStackTrace();
			logger.warn("the user with username: " + username + " is not exist;");
		}
		return salt;
	}

}
